package com.supcon.exchangedata.service.sw;

import com.supcon.exchangedata.pojo.entity.oracle.CtKpiDay;
import com.supcon.exchangedata.pojo.entity.oracle.StatistOtherParametersDay;
import com.supcon.exchangedata.pojo.entity.oracle.StatisticalRealTimeData;
import com.supcon.exchangedata.pojo.entity.mysql.operation.sw.SwSewageAll;
import com.supcon.exchangedata.pojo.entity.mysql.operation.sw.SwWaterAll;
import com.supcon.exchangedata.pojo.entity.mysql.operation.sw.WaterDailyOpertionInfo;
import com.supcon.exchangedata.repository.master.MasterKpiDayRepository;
import com.supcon.exchangedata.repository.master.MasterStatistOtherParametersDayRepository;
import com.supcon.exchangedata.repository.master.MasterStatisticalRealTimeDataRepository;
import com.supcon.exchangedata.repository.slave3.SlaveSwOperationInfo;
import com.supcon.exchangedata.repository.slave3.SlaveSwOperationInfo1;
import com.supcon.exchangedata.repository.slave3.SlaveSwOperationInfo2;
import com.supcon.exchangedata.repository.slave3.SlaveSwOperationInfo3;
import com.supcon.exchangedata.service.CommonMethodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yangbin
 * @Date: 2022/12/20/9:43
 * @Description:
 */
@Service
@Slf4j
public class SwOperationService {
    @Resource
    private MasterKpiDayRepository masterKpiDayRepository;

    @Resource
    private MasterStatistOtherParametersDayRepository masterStatistOtherParametersDayRepository;

    @Resource
    private CommonMethodService commonMethodService;


    @Resource
    private SlaveSwOperationInfo slaveSwOperationInfo;
    @Resource
    private SlaveSwOperationInfo1 slaveSwOperationInfo1;
    @Resource
    private SlaveSwOperationInfo2 slaveSwOperationInfo2;
    @Resource
    private SlaveSwOperationInfo3 slaveSwOperationInfo3;
    @Resource
    private MasterStatisticalRealTimeDataRepository masterStatisticalRealTimeDataRepository;

    /**
     * 获取最新一天水务日运营数据
     */
    public void dayOperationData() {
        WaterDailyOpertionInfo topData = slaveSwOperationInfo.findTopData();
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (topData != null) {
            LocalDateTime bizTime = topData.getBizTime();
            String dataTime = timeFormatter.format(bizTime);
            //供水量
            String waterSupplyAmount = topData.getWaterSupplyAmount();
            if (!StringUtils.isEmpty(waterSupplyAmount)) {
                BigDecimal bigDecimal = new BigDecimal(waterSupplyAmount);
                BigDecimal divide = bigDecimal.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                saveOrUpdateKpiDay("10000022150", dataTime, divide.toPlainString());
                saveOrUpdateStatistOtherParametersDay(2L, 20001L, dataTime, waterSupplyAmount);
            }

            //污水处理量
            String sewageAmount = topData.getWaterSewageAmount();
            if (!StringUtils.isEmpty(sewageAmount)) {
                BigDecimal bigDecimal = new BigDecimal(sewageAmount);
                BigDecimal divide = bigDecimal.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                saveOrUpdateKpiDay("10000022157", dataTime, divide.toPlainString());
                saveOrUpdateStatistOtherParametersDay(2L, 20004L, dataTime, sewageAmount);
            }
            //原水输送量
            String ysssl = topData.getYsssl();
            if (!StringUtils.isEmpty(ysssl)) {
                BigDecimal bigDecimal = new BigDecimal(ysssl);
                BigDecimal multiply = bigDecimal.multiply(new BigDecimal(10000));
                saveOrUpdateKpiDay("10000022876", dataTime, ysssl);
                saveOrUpdateStatistOtherParametersDay(2L, 20035L, dataTime, multiply.toPlainString());
                //保存原水输送量到redis
                if (!StringUtils.isEmpty(ysssl)) {
                    commonMethodService.saveRedis(ysssl, "万吨", dataTime, "10000022876");
                }

            }
            System.out.println(topData);

        }

    }

    /**
     * 获取最近一年日运营数据
     */
    public void dayOperationByYear(LocalDateTime startTime, LocalDateTime endTime) {
        List<WaterDailyOpertionInfo> allByBizTimeBetween = slaveSwOperationInfo.findAllByBizTimeBetween(startTime, endTime);
        if (!CollectionUtils.isEmpty(allByBizTimeBetween)) {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (WaterDailyOpertionInfo topData : allByBizTimeBetween) {

                if (topData != null) {
                    LocalDateTime bizTime = topData.getBizTime();
                    String dataTime = timeFormatter.format(bizTime);
                    //供水量
                    String waterSupplyAmount = topData.getWaterSupplyAmount();
                    if (!StringUtils.isEmpty(waterSupplyAmount)) {
                        BigDecimal bigDecimal = new BigDecimal(waterSupplyAmount);
                        BigDecimal divide = bigDecimal.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                        saveOrUpdateKpiDay("10000022150", dataTime, divide.toPlainString());
                        saveOrUpdateStatistOtherParametersDay(2L, 20001L, dataTime, waterSupplyAmount);
                    }

                    //污水处理量
                    String sewageAmount = topData.getWaterSewageAmount();
                    if (!StringUtils.isEmpty(sewageAmount)) {
                        BigDecimal bigDecimal = new BigDecimal(sewageAmount);
                        BigDecimal divide = bigDecimal.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                        saveOrUpdateKpiDay("10000022157", dataTime, divide.toPlainString());
                        saveOrUpdateStatistOtherParametersDay(2L, 20004L, dataTime, sewageAmount);
                    }
                    //原水输送量
                    String ysssl = topData.getYsssl();
                    if (!StringUtils.isEmpty(ysssl)) {
                        BigDecimal bigDecimal = new BigDecimal(ysssl);
                        BigDecimal multiply = bigDecimal.multiply(new BigDecimal(10000));
                        saveOrUpdateKpiDay("10000022876", dataTime, ysssl);
                        saveOrUpdateStatistOtherParametersDay(2L, 20035L, dataTime, multiply.toPlainString());
                    }
                    System.out.println(topData);

                }
            }

        }

    }


    /**
     * 获取供水最新数据
     */
    public void dayWaterOperationData() {
        SwWaterAll topData = slaveSwOperationInfo2.findTopData();
        if (topData != null) {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime bizTime = topData.getBizTime();
            String dataTime = timeFormatter.format(bizTime);
            Long type = 20001L;
            //闲林  99416L
            String xianlinValue = topData.getXianlinValue();
            if (!StringUtils.isEmpty(xianlinValue)) {
                saveOrUpdateStatistOtherParametersDay(99416L, type, dataTime, xianlinValue);
                saveRealTimeData(xianlinValue, 99416L, type);
            }

            // 滨江 100735L
            String binjiangValue = topData.getBinjiangValue();
            if (!StringUtils.isEmpty(binjiangValue)) {
                saveOrUpdateStatistOtherParametersDay(100735L, type, dataTime, binjiangValue);
                saveRealTimeData(binjiangValue, 100735L, type);
            }
            // 富阳 100935L
            String fuyangValue = topData.getFuyangValue();
            if (!StringUtils.isEmpty(fuyangValue)) {
                saveOrUpdateStatistOtherParametersDay(100935L, type, dataTime, fuyangValue);
                saveRealTimeData(fuyangValue, 100935L, type);
            }
            // 临安 100701L
            String linanValue = topData.getLinanValue();
            if (!StringUtils.isEmpty(linanValue)) {
                saveOrUpdateStatistOtherParametersDay(100701L, type, dataTime, linanValue);
                saveRealTimeData(linanValue, 100701L, type);
            }
            // 建德 100700L
            String jiandeValue = topData.getJiandeValue();
            if (!StringUtils.isEmpty(jiandeValue)) {
                saveOrUpdateStatistOtherParametersDay(100700L, type, dataTime, jiandeValue);
                saveRealTimeData(jiandeValue, 100700L, type);
            }
            // 祥符 20865L
            String xiangfuValue = topData.getXiangfuValue();
            if (!StringUtils.isEmpty(xianlinValue)) {
                saveOrUpdateStatistOtherParametersDay(20865L, type, dataTime, xiangfuValue);
                saveRealTimeData(xiangfuValue, 20865L, type);
            }
            // 赤山埠 20866L
            String chishanbuValue = topData.getChishanbuValue();
            if (!StringUtils.isEmpty(xianlinValue)) {
                saveOrUpdateStatistOtherParametersDay(20866L, type, dataTime, chishanbuValue);
                saveRealTimeData(chishanbuValue, 20866L, type);
            }
            // 清泰 20864L
            String qingtaiValue = topData.getQingtaiValue();
            if (!StringUtils.isEmpty(xianlinValue)) {
                saveOrUpdateStatistOtherParametersDay(20864L, type, dataTime, qingtaiValue);
                saveRealTimeData(qingtaiValue, 20864L, type);
            }
            // 南星 20867L
            String nanxingValue = topData.getNanxingValue();
            if (!StringUtils.isEmpty(xianlinValue)) {
                saveOrUpdateStatistOtherParametersDay(20867L, type, dataTime, nanxingValue);
                saveRealTimeData(nanxingValue, 20867L, type);
            }
            // 九溪 20868L
            String jiuxiValue = topData.getJiuxiValue();
            if (!StringUtils.isEmpty(xianlinValue)) {
                saveOrUpdateStatistOtherParametersDay(20868L, type, dataTime, jiuxiValue);
                saveRealTimeData(jiuxiValue, 20868L, type);
            }
            // 总供水量
            String totalSupply = topData.getTotalSupply();
            if (!StringUtils.isEmpty(totalSupply)) {
                saveOrUpdateStatistOtherParametersDay(2L, type, dataTime, totalSupply);
                saveRealTimeData(totalSupply, 2L, type);

                BigDecimal bigDecimal = new BigDecimal(totalSupply);
                BigDecimal divide = bigDecimal.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                saveOrUpdateKpiDay("10000022150", dataTime, divide.toPlainString());
                if (!StringUtils.isEmpty(totalSupply)) {
                    commonMethodService.saveRedis(divide.toPlainString(), "万吨", dataTime, "10000022150");
                }
            }


        }
    }


    /**
     * 获取供水最近一年数据
     */
    public void dayWaterByYearData(LocalDateTime startTime, LocalDateTime endTime) {
        List<SwWaterAll> allByBizTimeBetween = slaveSwOperationInfo2.findAllByBizTimeBetween(startTime, endTime);
        Long type = 20001L;
        if (!CollectionUtils.isEmpty(allByBizTimeBetween)) {
            for (SwWaterAll topData : allByBizTimeBetween) {
                if (topData != null) {
                    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDateTime bizTime = topData.getBizTime();
                    String dataTime = timeFormatter.format(bizTime);

                    //闲林  99416L
                    String xianlinValue = topData.getXianlinValue();
                    if (!StringUtils.isEmpty(xianlinValue)) {
                        saveOrUpdateStatistOtherParametersDay(99416L, type, dataTime, xianlinValue);
                    }

                    // 滨江 100735L
                    String binjiangValue = topData.getBinjiangValue();
                    if (!StringUtils.isEmpty(binjiangValue)) {
                        saveOrUpdateStatistOtherParametersDay(100735L, type, dataTime, binjiangValue);
                    }
                    // 富阳 100935L
                    String fuyangValue = topData.getFuyangValue();
                    if (!StringUtils.isEmpty(fuyangValue)) {
                        saveOrUpdateStatistOtherParametersDay(100935L, type, dataTime, fuyangValue);
                    }
                    // 临安 100701L
                    String linanValue = topData.getLinanValue();
                    if (!StringUtils.isEmpty(linanValue)) {
                        saveOrUpdateStatistOtherParametersDay(100701L, type, dataTime, linanValue);
                    }
                    // 建德 100700L
                    String jiandeValue = topData.getJiandeValue();
                    if (!StringUtils.isEmpty(jiandeValue)) {
                        saveOrUpdateStatistOtherParametersDay(100700L, type, dataTime, jiandeValue);
                    }
                    // 祥符 20865L
                    String xiangfuValue = topData.getXiangfuValue();
                    if (!StringUtils.isEmpty(xianlinValue)) {
                        saveOrUpdateStatistOtherParametersDay(20865L, type, dataTime, xiangfuValue);
                    }
                    // 赤山埠 20866L
                    String chishanbuValue = topData.getChishanbuValue();
                    if (!StringUtils.isEmpty(xianlinValue)) {
                        saveOrUpdateStatistOtherParametersDay(20866L, type, dataTime, chishanbuValue);
                    }
                    // 清泰 20864L
                    String qingtaiValue = topData.getQingtaiValue();
                    if (!StringUtils.isEmpty(xianlinValue)) {
                        saveOrUpdateStatistOtherParametersDay(20864L, type, dataTime, qingtaiValue);
                    }
                    // 南星 20867L
                    String nanxingValue = topData.getNanxingValue();
                    if (!StringUtils.isEmpty(xianlinValue)) {
                        saveOrUpdateStatistOtherParametersDay(20867L, type, dataTime, nanxingValue);
                    }
                    // 九溪 20868L
                    String jiuxiValue = topData.getJiuxiValue();
                    if (!StringUtils.isEmpty(xianlinValue)) {
                        saveOrUpdateStatistOtherParametersDay(20868L, type, dataTime, jiuxiValue);
                    }
                    // 主城区

                }
            }

        }


    }


    /**
     * 获取污水最新数据
     */
    public void daySewageOperationData() {
        SwSewageAll topData = slaveSwOperationInfo1.findTopData();
        if (topData != null) {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime bizTime = topData.getBizTime();
            String dataTime = timeFormatter.format(bizTime);
            Long type = 20004L;

            // 总污水处理量
            String totalSewage = topData.getTotalSewage();
            if (!StringUtils.isEmpty(totalSewage)) {
                BigDecimal bigDecimal1 = new BigDecimal(totalSewage);
            /*    if(bigDecimal1.compareTo(new BigDecimal("1000000")) > 0){*/
                    saveOrUpdateStatistOtherParametersDay(2L, type, dataTime, totalSewage);
                    saveRealTimeData(totalSewage, 2L, type);
                    BigDecimal bigDecimal = new BigDecimal(totalSewage);
                    BigDecimal divide = bigDecimal.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
                    saveOrUpdateKpiDay("10000022157", dataTime, divide.toPlainString());
                    if (!StringUtils.isEmpty(totalSewage)) {
                        commonMethodService.saveRedis(divide.toPlainString(), "万吨", dataTime, "10000022157");
                    }
                /*}else {
                    return;
                }*/
            }

            //城西污水厂 20872
            String chengxiValue = topData.getChengxiValue();
            if (!StringUtils.isEmpty(chengxiValue)) {
                saveOrUpdateStatistOtherParametersDay(20872L, type, dataTime, chengxiValue);
                saveRealTimeData(chengxiValue, 20872L, type);
            }
            // 城东污水厂 193379
            String chengdongValue = topData.getChengdongValue();
            if (!StringUtils.isEmpty(chengdongValue)) {
                saveOrUpdateStatistOtherParametersDay(193379L, type, dataTime, chengdongValue);
                saveRealTimeData(chengdongValue, 193379L, type);
            }
            // 临安污水 100702
            String laValue = topData.getLaValue();
            if (!StringUtils.isEmpty(laValue)) {
                saveOrUpdateStatistOtherParametersDay(100702L, type, dataTime, laValue);
                saveRealTimeData(laValue, 100702L, type);
            }
            // 建德污水 100703
            String jdValue = topData.getJdValue();
            if (!StringUtils.isEmpty(chengdongValue)) {
                saveOrUpdateStatistOtherParametersDay(100703L, type, dataTime, jdValue);
                saveRealTimeData(jdValue, 100703L, type);
            }
            // 富阳污水处理量 10070421
            String fyValue = topData.getFyValue();
            if (!StringUtils.isEmpty(fyValue)) {
                saveOrUpdateStatistOtherParametersDay(10070421L, type, dataTime, fyValue);
                saveRealTimeData(fyValue, 10070421L, type);
            }


        }
    }

    public void daySewageOperationByYearData(LocalDateTime startTime, LocalDateTime endTime) {
        List<SwSewageAll> allByBizTimeBetween = slaveSwOperationInfo1.findAllByBizTimeBetween(startTime, endTime);
        if (!CollectionUtils.isEmpty(allByBizTimeBetween)) {
            for (SwSewageAll topData : allByBizTimeBetween) {
                if (topData != null) {
                    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDateTime bizTime = topData.getBizTime();
                    String dataTime = timeFormatter.format(bizTime);
                    Long type = 20004L;
                    //城西污水厂 20872
                    String chengxiValue = topData.getChengxiValue();
                    if (!StringUtils.isEmpty(chengxiValue)) {
                        saveOrUpdateStatistOtherParametersDay(20872L, type, dataTime, chengxiValue);
                        saveRealTimeData(chengxiValue, 20872L, type);
                    }
                    // 城东污水厂 193379
                    String chengdongValue = topData.getChengdongValue();
                    if (!StringUtils.isEmpty(chengdongValue)) {
                        saveOrUpdateStatistOtherParametersDay(193379L, type, dataTime, chengdongValue);
                        saveRealTimeData(chengdongValue, 193379L, type);
                    }
                    // 临安污水 100702
                    String laValue = topData.getLaValue();
                    if (!StringUtils.isEmpty(laValue)) {
                        saveOrUpdateStatistOtherParametersDay(100702L, type, dataTime, laValue);
                        saveRealTimeData(laValue, 100702L, type);
                    }
                    // 建德污水 100703
                    String jdValue = topData.getJdValue();
                    if (!StringUtils.isEmpty(chengdongValue)) {
                        saveOrUpdateStatistOtherParametersDay(100703L, type, dataTime, jdValue);
                        saveRealTimeData(jdValue, 100703L, type);
                    }
                    // 富阳污水处理量 10070421
                    String fyValue = topData.getFyValue();
                    if (!StringUtils.isEmpty(fyValue)) {
                        saveOrUpdateStatistOtherParametersDay(10070421L, type, dataTime, fyValue);
                        saveRealTimeData(fyValue, 10070421L, type);
                    }
                }
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateKpiDay(String code, String day, String value) {
        String pattern = "[0-9]*\\.?[0-9]*";
        if (StringUtils.isEmpty(value) || !value.matches(pattern)) {
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime dayOfMonthKey = LocalDate.parse(day, dateTimeFormatter).atStartOfDay();
        CtKpiDay byCodeAndDayOfMonthKey = masterKpiDayRepository.findByCodeAndDayOfMonthKey(code, dayOfMonthKey);
        if (byCodeAndDayOfMonthKey == null) {
            byCodeAndDayOfMonthKey = new CtKpiDay();
            byCodeAndDayOfMonthKey.setCode(code);
            byCodeAndDayOfMonthKey.setDayOfMonthKey(dayOfMonthKey);
            byCodeAndDayOfMonthKey.setLastUpdateTime(LocalDateTime.now());
            byCodeAndDayOfMonthKey.setDataType(code);

        }
        byCodeAndDayOfMonthKey.setCurrentValue(value);
        masterKpiDayRepository.save(byCodeAndDayOfMonthKey);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateStatistOtherParametersDay(Long objId, Long type, String day, String value) {
        String pattern = "[0-9]*\\.?[0-9]*";
        if (StringUtils.isEmpty(value) || !value.matches(pattern)) {
            return;
        }

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime dayOfMonthKey = LocalDate.parse(day, dateTimeFormatter).atStartOfDay();
        StatistOtherParametersDay byObjIdAndTypeAndDayOfMonthKey = masterStatistOtherParametersDayRepository.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
        if (byObjIdAndTypeAndDayOfMonthKey == null) {
            byObjIdAndTypeAndDayOfMonthKey = new StatistOtherParametersDay();
            byObjIdAndTypeAndDayOfMonthKey.setObjId(objId);
            byObjIdAndTypeAndDayOfMonthKey.setType(type);
            byObjIdAndTypeAndDayOfMonthKey.setDayOfMonthKey(dayOfMonthKey);
            byObjIdAndTypeAndDayOfMonthKey.setObjType(1L);
            byObjIdAndTypeAndDayOfMonthKey.setLastTime(LocalDateTime.now());
            byObjIdAndTypeAndDayOfMonthKey.setInAvgValue(Double.valueOf(value));
            masterStatistOtherParametersDayRepository.save(byObjIdAndTypeAndDayOfMonthKey);
        } else {
            masterStatistOtherParametersDayRepository.updateDay(Double.valueOf(value), objId, dayOfMonthKey, type);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    public void saveRealTimeData(String value, Long objId, Long dataType) {
        BigDecimal targetValue = new BigDecimal(0);
        try {
            targetValue = new BigDecimal(value);
        } catch (Exception e) {
            log.info("错误:" + e.getMessage());
        }

        StatisticalRealTimeData realTimeData = new StatisticalRealTimeData();
        realTimeData.setSumType(1L);
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate now = LocalDate.now();
        String format1 = dateTimeFormatter1.format(now);
        realTimeData.setCurMonth(format1);
        realTimeData.setObjId(objId);
        realTimeData.setObjType(1L);
        realTimeData.setDataType(dataType);
        realTimeData.setId(0);
        realTimeData.setCurDate(now.atStartOfDay());
        realTimeData.setCurDateValue(targetValue);
        realTimeData.setLastupdatetime(LocalDateTime.now());
        masterStatisticalRealTimeDataRepository.save(realTimeData);
    }

}
